import React, {useEffect, useState} from "react"
import {Tabs, TabsProps} from "antd";

export interface LazyTabsProps extends TabsProps {
    lazyItems: LazyItem[]
}

export interface LazyItem {
    key: string
    label: string
    render: () => React.ReactNode
}

const LazyTabs: React.FC<LazyTabsProps> = (props) => {
    const [activatedKey, setActivatedKey] = useState(props.activeKey ?? props.defaultActiveKey)
    return (
        <>
            <Tabs {...props} items={props.lazyItems.map(it => ({
                key: it.key,
                label: it.label,
                children: <LazyTabItemComponent myKey={it.key} activatedKey={activatedKey} render={it.render}/>,
            }))} onChange={value => {
                setActivatedKey(value);
                props.onChange && props.onChange(value)
            }}>

            </Tabs>
        </>
    )
}

const LazyTabItemComponent: React.FC<{
    activatedKey?: string,
    myKey: string,
    render: () => React.ReactNode
}> = (props) => {
    const [loaded, setLoaded] = useState(false)
    useEffect(() => {
        if (!loaded) {
            setLoaded(props.activatedKey === props.myKey)
        }
    }, [props.activatedKey, props.myKey]);
    return (
        <>
            {loaded && props.render()}
        </>
    )
}

export default LazyTabs
